/*
 *  Copyright 2007 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.servlet;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.util.RequestUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Locale;
import java.text.ParseException;

import com.blandware.atleap.common.util.DateUtil;
import com.blandware.atleap.common.Constants;
import com.blandware.atleap.service.core.BackupManager;
import com.blandware.atleap.webapp.util.core.GlobalProperties;

/**
 * <p>Servlet that is used to download DB backups.</p>
 * <p>Following attributes are accepted:
 * <ul>
 * <li>
 * <code>date</code> -- date of DB backup (formatted according to current locale).
 * </li>
 * </ul>
 * </p>
 * <p><a href="DbBackupServlet.java.html"><i>View source</i></a></p>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.1 $ $Date: 2007/06/06 13:43:02 $
 * @web.servlet name="dbBackup" load-on-startup="1"
 * @web.servlet-mapping url-pattern="/servlet/dbBackup/*"
 */
public class DbBackupServlet extends HttpServlet {
	/**
	 * Commons Logging instance.
	 */
	protected transient final Log log = LogFactory.getLog(ResourceServlet.class);

	/**
	 * Initializes the servlet.
	 */
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}

	/**
	 * Destroys the servlet.
	 */
	public void destroy() {
        super.destroy();
	}

	/**
	 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
	 *
	 * @param request  servlet request
	 * @param response servlet response
     * @throws java.io.IOException If something is wrong with I/O
	 */
	protected void processRequest(HttpServletRequest request,
                                  HttpServletResponse response)
            throws IOException {
		//check roles
        boolean granted = request.isUserInRole("core-backup-download");

        if (!granted) {
			// The current user is not authorized for this action
			if ( log.isDebugEnabled() ) {
				log.debug(" User '" + request.getRemoteUser() +
				        "' does not have a required role to download, denying access");
			}
			response.sendError(HttpServletResponse.SC_FORBIDDEN);
			return;
		}

        // check that feature is enabled
        GlobalProperties globalProperties = GlobalProperties.getInstance(request.getSession().getServletContext());
        boolean enabled = "true".equalsIgnoreCase(globalProperties.getString("dbbackup.download", "false"));
        if (!enabled) {
            // This feature is disabled
            if (log.isDebugEnabled()) {
                log.debug("DB backup download is disabled in build properties, denying access");
            }
			response.sendError(HttpServletResponse.SC_FORBIDDEN);
			return;
        }

        String dateString = null;
		if (request.getParameter("date") != null) {
			dateString = request.getParameter("date");
		} else if (request.getAttribute("date") != null) {
			dateString = (String) request.getAttribute("date");
		} else {
			String message = "Missing 'date' parameter in the request";
			if ( log.isWarnEnabled() ) {
				log.warn(message);
			}
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}

        Date date = null;
        if (dateString != null) {
            try {
                Locale locale = RequestUtils.getUserLocale(request, null);
                date = DateUtil.parseDateTime(dateString, locale);
            } catch (ParseException ex) {
                if ( log.isWarnEnabled() ) {
                    log.warn("Bad date: cannot parse ('" + dateString + "')");
                }
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Date: " + date);
        }

        ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
        BackupManager backupManager = (BackupManager) ctx.getBean(Constants.BACKUP_MANAGER_BEAN);

        String fileName = backupManager.getBackupFileName(date);
        byte[] bytes = backupManager.getBackupFileData(date);

        if (bytes == null) {
            // error occured, nothing is returned
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Transfer-Encoding", "binary");

		OutputStream out = response.getOutputStream();
		response.setContentLength(bytes.length);
		out.write(bytes);
		out.flush();
		out.close();
    }

    /**
	 * Handles the HTTP <code>GET</code> method.
	 *
	 * @param request  servlet request
	 * @param response servlet response
	 */
	protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws IOException {
		processRequest(request, response);
	}

	/**
	 * Handles the HTTP <code>POST</code> method.
	 *
	 * @param request  servlet request
	 * @param response servlet response
	 */
	protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws IOException {
		processRequest(request, response);
	}

	/**
	 * Returns a short description of the servlet.
	 */
	public String getServletInfo() {
		return "Servlet to return DB backup";
	}
}
